package cn.zhagzheguo.xk.dao.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cn.zhagzheguo.xk.dao.CommentDao;
import cn.zhagzheguo.xk.model.Comment;
import cn.zhagzheguo.xk.status.CommonStatus;

@Repository
public class CommentDaoImpl implements CommentDao {

	@Autowired
	SqlSessionFactory sqlSessionFactory;

	@Override
	public int insert(Comment comment) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			session.insert("cn.zhagzheguo.xk.mapper.CommentMapper.insert", comment);
			session.commit();
			return CommonStatus.SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			session.rollback();
			return CommonStatus.FAIL;
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	@Override
	public List<Comment> getAllByCourseId(int course_id) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			List<Comment> list = session.selectList("cn.zhagzheguo.xk.mapper.CommentMapper.selectList_course",
					course_id);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	@Override
	public int delete(int comment_id) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			session.delete("cn.zhagzheguo.xk.mapper.CommentMapper.delete", comment_id);
			session.commit();
			return CommonStatus.SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			session.rollback();
			return CommonStatus.FAIL;
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	public static void main(String[] args) {
		CommentDao cd = new CommentDaoImpl();
		Comment c = new Comment();
		c.setCourse_id(2);
		c.setStu_id(2);
		c.setDate("2016-9-12 08:48");
		c.setGreat(0);
		c.setContent("啊啊啊啊啊");
		cd.insert(c);

		List<Comment> list = cd.getAllByCourseId(1);
		System.out.println(list.toString());
	}
}
